package com.xzz.tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author: hhz
 * @create: 2022-01-20 17:05
 * 117. 填充每个节点的下一个右侧节点指针 II
 **/
public class Connect2 {
    public static void main(String[] args) {
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);
        Node node5 = new Node(5);
        Node node6 = new Node(7);
        node1.left = node2;
        node1.right = node3;
        node2.left = node4;
        node2.right = node5;
        node3.right = node6;

        Node connect = connect(node1);
        System.out.println();

    }
    public static Node connect(Node root) {
        if(root == null){
            return null;
        }
        Queue<Node> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            int size = queue.size();
            Node pre = null;
            for (int i = 0; i < size; i++) {
                Node poll = queue.poll();
                if(pre !=null){
                    pre.next = poll;
                }
                pre = poll;

                if(poll.left!=null){
                    queue.offer(poll.left);
                }
                if(poll.right!=null){
                    queue.offer(poll.right);
                }

            }
        }
        return root;

    }
}
